#include <node.h>
#include <v8.h>
#include <openssl/md5.h>
#include <string.h>
#include <string>
 
using namespace v8;

void openssl_md5(const char * data, int size, unsigned char * buf) {
	MD5_CTX c;
	MD5_Init(&c);
	MD5_Update(&c, data, size);
	MD5_Final(buf, &c);
}
 
Handle<Value> GetMD5(const Arguments& args) {
	HandleScope scope;
	
	//std::string password = args[0].As<String>().Utf8Value();
	
	String::Utf8Value val(args[0]);
	std::string password(*val);
	printf("md5 in str:%s %ld\n", password.c_str(), password.size());
	unsigned char hash[16];
	memset(hash, 0, 16);
	openssl_md5(password.c_str(), password.size(), hash);
	char tmp[3];
	char md5str[33] = {};
	int i;
	for (i = 0; i < 16; i++) {
		sprintf(tmp, "%02x", hash[i]);
		strcat(md5str, tmp);
	}
	
	return scope.Close(String::New(md5str, 32));
}
 
void init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("md5"),
      FunctionTemplate::New(GetMD5)->GetFunction());
}
 
NODE_MODULE(hello, init)
